<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getTurnoverStatisticsService } from '@/api/report'

const props = defineProps({
  dateRange: {
    type: Object,
    required: true
  }
})

const chart = ref(null) // 获取DOM引用
let myChart = null // 持久化图表实例
const dateList = ref() // 日期列表
const turnoverList = ref() // 每日营业额列表

const getTurnoverStatistics = async () => {
  const res = await getTurnoverStatisticsService(props.dateRange)
  dateList.value = res.data.data.dateList
  turnoverList.value = res.data.data.turnoverList
  updateChart()
}

// 初始化图表基础配置
const initChart = () => {
  myChart = echarts.init(chart.value)
  const baseOption = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const dataItem = params[0]
        return (
          `${dataItem.axisValue}<br/>` +
          `${dataItem.marker}${dataItem.seriesName}：<b>¥${dataItem.value.toFixed(2)}</b><br/>`
        )
      }
    },
    grid: {
      left: '1%',
      right: '1%',
      bottom: '3%',
      top: '4%',
      containLabel: true
    },
    xAxis: {
      type: 'category'
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '营业额',
        type: 'line',
        smooth: true
      }
    ]
  }

  myChart.setOption(baseOption)
}

// 更新图表数据
const updateChart = () => {
  const option = {
    xAxis: {
      data: dateList.value
    },
    series: [
      {
        data: turnoverList.value
      }
    ]
  }
  myChart.setOption(option)
}

onMounted(() => {
  initChart()
})

watch(() => props.dateRange, getTurnoverStatistics, { immediate: true })
</script>

<template>
  <div ref="chart" style="width: 100%; height: 350px"></div>
</template>
